package com.sxj.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石小俊
 * @date 2024年03月02日 13:46
 */
// loadOnStartup属性:更改初始化方法的执行时机,将其设置为服务器启动时执行
@WebServlet(urlPatterns = "/life", loadOnStartup = 1, initParams = {
        @WebInitParam(name = "username", value = "root"),
        @WebInitParam(name = "password", value = "123456")
})
public class LifeServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        // 第一次访问该Servlet时,执行初始化方法,且初始化方法只执行一次
        System.out.println("***************初始化***************");
    }

    // service:处理一切请求
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 每次访问Servlet都会执行对应的核心业务逻辑
        System.out.println("***************执行核心业务逻辑***************");
        String username = getInitParameter("username");
        String password = getInitParameter("password");
        System.out.println("username:" + username + ",password:" + password);
    }

    // doXxx方法表示只能处理对应Xxx的请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("***************执行get请求***************");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("***************执行post请求***************");
    }

    @Override
    public void destroy() {
        // 当服务器停止时,执行销毁方法
        System.out.println("***************销毁***************");
    }
}
